<?php

namespace common\rest\grid;

use common\helpers\ArrayHelper;

/**
 * LabelColumn displays a column of mark text content in a grid view.
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 */
class LabelColumn extends DataColumn {

    public $format = 'mark';

    public function getModelMarksOption() {
        $relatedModel = $this->grid;
        $attributeParts = explode('.', $this->attribute);
        $neededAttribute = array_pop($attributeParts);
        if (!empty($attributeParts)) {
            foreach ($attributeParts as $relationName) {
                if ($relatedModel->isRelationPopulated($relationName) && $relatedModel->$relationName instanceof \common\db\ActiveRecord) {
                    $relatedModel = $relatedModel->$relationName;
                } else {
                    try {
                        $relation = $relatedModel->getRelation($relationName);
                    } catch (InvalidParamException $e) {
                        return $relatedModel = $this->grid;
                    }
                    /* @var $modelClass ActiveRecordInterface */
                    $modelClass = $relation->modelClass;
                    $relatedModel = $modelClass::instance();
                }
            }
        }
        if ($relatedModel instanceof \common\db\ActiveRecord) {
            return $relatedModel::getMarksOptionList($neededAttribute);
        }
        return null;
    }

    /**
     * Returns the data cell value.
     * @param mixed $model the data model
     * @param mixed $key the key associated with the data model
     * @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]].
     * @return string the data cell value
     */
    public function renderExtands() {
        $options = [];
        $options['data'] = $this->getModelMarksOption();
        return $options;
    }

}
